package com.jackrain.nea.shiro.stateful;

import com.jackrain.nea.core.query.QueryException;
import com.jackrain.nea.util.RedisOpsUtil;
import com.jackrain.nea.web.face.impl.UserImpl;
import com.jackrain.nea.web.security.Security4Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;

/**
 * Created by nathan on 2016/7/26.
 */
@Component
@Slf4j
public class MyAuthenticationListener implements AuthenticationListener {

    private static Logger logger= LoggerFactory.getLogger(MyAuthenticationListener.class.getName());

    //private SecurityWebUtils securityWebUtils;


    @Autowired
    private RedisOpsUtil<String,String> redisOpsUtil;

    @Autowired
    private CachingShiroSessionDao sessionDao;

    @Override
    public void onSuccess(AuthenticationToken token, AuthenticationInfo info) {
        UsernamePasswordToken authToken = (UsernamePasswordToken)token;
        UserImpl u = info.getPrincipals().oneByType(UserImpl.class);
        u.setLastloginip(authToken.getHost());
        u.setLastlogindate(new Date());
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession(true);
        try {
            Security4Utils.setUserWithSuccess(u);
            session.setAttribute("user",u);
        } catch (QueryException e) {
            log.error(e.getMessage(),e);
        }
    }

    @Override
    public void onFailure(AuthenticationToken token, AuthenticationException ae) {
        UsernamePasswordToken authToken = (UsernamePasswordToken)token;
        String username = authToken.getUsername();
        UserImpl user = new UserImpl();
        String IP = authToken.getHost();
        user.setName(username);
        user.setLastloginip(IP);
        try {
            Security4Utils.setUserWithFailure(user);
        } catch (QueryException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onLogout(PrincipalCollection principals) {

    }
}
